package top.ffhome.system.service.impl;

import java.util.List;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import top.ffhome.common.audit.AuditOperation;
import top.ffhome.common.audit.AuditService;
import top.ffhome.common.service.impl.BaseServiceImpl;
import top.ffhome.system.constant.SysConstants;
import top.ffhome.system.entity.SysMenu;
import top.ffhome.system.mapper.SysMenuMapper;
import top.ffhome.system.service.SysMenuService;
import top.ffhome.util.core.TreeUtil;

@Service
@AuditService(entity = SysMenu.class)
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenu, SysMenuMapper> implements SysMenuService {
	@Override
	@CacheEvict(value = { "menu_getTree" }, allEntries = true)
	public void clearCache() {
	}

	@Override
	@Cacheable(value = "menu_getTree", unless = "#result == null || #result.size() == 0")
	public List<SysMenu> getTree() {
		SysMenu dto = new SysMenu();
		dto.setStatus(SysConstants.NORMAL);
		dto.getParams().put("fields", "m.id,m.parent_id,m.label,m.sort");
		dto.getParams().put("orderBy", "sort");
		List<SysMenu> list = mapper.select(dto);
		return TreeUtil.generate(list, new SysMenu());
	}

	@Override
	@AuditOperation(type = AuditOperation.UPDATE)
	public void move(SysMenu menu) {
		if (menu.getSort() == 0) {
			Integer max = mapper.getMaxSortByParentId(menu.getParentId());
			if (max == null) {
				max = 0;
			}
			menu.setSort(max + 1);
		} else {
			mapper.moveNextSiblingsSort(menu.getParentId(), menu.getSort());
		}
		mapper.update(menu);
		getSelf().clearCache();
	}
}
